/**
 * @file demo
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-01-07
 */
/* eslint-disable */
import {useEffect, useState, useCallback, useMemo} from 'react';
import {Card, Space, Row, Spin, Table, Input, Col} from 'antd';
import moment from 'moment';

import {
    getTransformValues,
    fetchSearchFormOptions,
    fetchDetail,
    downLoad
} from '~/service/reportsChart';
import CommonSearchBar from '../common/CommonSearchBar';

import {getFirstAndLastTimestamp, YESTERDAY} from '~/utils/date';
import TransformTextCard from './components/TransformTextCard';
import EchartsPieCard from '../common/EchartsPieCard';
import EchartsLineCard from '../common/EchartsLineCard';
import ProgressCardList from './components/ProgressCardList';
import DetailModal from '../common/DetailModal';
import CommonTitle from '../common/Title';
import {searchForm, getDimensionId, dashBoardList, pageId} from './config';
import {parsePercent, numberHandle} from '~/utils/number';
import {formatTooltip} from '../utils/formatTooltip';

import './index.styl';

const {TextArea} = Input;

const initialValues = {
    clazzStatus: ['行课中', '已结课'],
    startClassTime: getFirstAndLastTimestamp({format: 'YYYY-MM-DD'})
};

export default function TransformReport(props) {
    // const {match: {params: {id}}} = props;
    const [loading, setLoading] = useState(false);
    const [result, setResult] = useState();
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    const [drilingList, setDrilingList] = useState([]);
    const [drilingLevel, setDrilingLevel] = useState(null);
    const [detailData, setDetailData] = useState({});
    const [detailModalVisible, setDetailModalVisible] = useState(false);

    // 获取全局数据
    const getData = (params = searchFormValues) => {
        setLoading(true);

        const {startClassTime} = params;
        const [begin, end] = startClassTime || [];
        const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
        const endRangeTime = end && moment(end).format('YYYY-MM-DD');
        params.beginTime = [beginRangeTime, endRangeTime];
        params.dashBoardList = dashBoardList;

        getTransformValues(params)
            .then(res => {
                const {
                    data
                } = res;

                setResult(data);
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const handleDetail = unit => {
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList,
            dashBoardList
        };

        setDetailModalVisible(true);
        fetchDetail(params)
            .then(res => {
                setDetailData(res.data || {});
            });
    };

    const handleDownload = unit => {
        const params = {
            ...searchFormValues,
            ...unit,
            drilingList,
            dashBoardList
        };
        const excelName = unit.unitName;

        downLoad({params, excelName});
    };

    const handleBack = async params => {
        console.log('返回', params);
        const {unitId, unitName} = params;
        // 所有下钻取消
        setDrilingList([]);

        try {
            await getData(searchFormValues);
            // 返回搜索数据接口调用成功后level - 1
            setDrilingLevel({unitId, level: 0});
        }
        catch {}
    };

    const handleDrilling = async params => {
        console.log('下钻', params);
        const {unitId, unitName, info} = params;

        const driling = {
            unitId,
            unitName,
            value: info.name
        };

        setDrilingList([driling]);

        try {
            await getData({...searchFormValues, drilingList: [driling]});
            // 搜索接口调用成功后level + 1
            setDrilingLevel({unitId, level: 1});
        }
        catch {}
    };

    useEffect(() => {
        getData();
    }, []);

    // 表单确定
    const handleOk = fieldsValue => {
        setSearchFormValues(fieldsValue);
        setDrilingLevel(null);
        setDrilingList([]);
        getData(fieldsValue);
    };

    // 表单重置
    const handleReset = e => {
        setSearchFormValues(initialValues);
        setDrilingLevel(null);
        setDrilingList([]);
        getData(initialValues);
    };

    // 表单change
    const handleItemChange = itemKeyValue => {
        // setSearchFormValues({...searchFormValues, ...itemKeyValue});
        console.log('handleItemChange', itemKeyValue);
    };

    // 请求单个表单配置项
    const handleFetchOptions = ({key, searchKey, pager, dependItemKey, dependItemValue, isGetingMore, options: curOptions, fieldsValue}) => {
        let permissions = searchForm.map(item => {
            if (item.key === 'startClassTime') {
                const [begin, end] = fieldsValue[item.key] || [];
                const beginRangeTime = begin && moment(begin).format('YYYY-MM-DD');
                const endRangeTime = end && moment(end).format('YYYY-MM-DD');
                const filterItems = [beginRangeTime, endRangeTime];
                const dimensionId = getDimensionId(0, 'beginTime');

                return (
                    {
                        dimensionId,
                        dimensionName: 'beginTime',
                        filterItems
                    }
                )
            }
            return (
                {
                    dimensionId: getDimensionId(0, item.key),
                    dimensionName: item.key,
                    filterItems: fieldsValue[item.key]
                }
            )
        })

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: getDimensionId(0, key),
            dimensionName: key,
            searchKey,
            permissions,
            dashBoardList,
            unitId: pageId[0].selectID
        };

        fetchSearchFormOptions(params)
            .then(res => {
                const {data, pager} = res;

                let options = data.map(item => (
                    {
                        key: item,
                        value: item,
                        label: item
                    }
                )) || [];

                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }

                setSelectOptions({key, options, pager});
            });
    };

    return (
        <div className="transform-report-container">
            <CommonTitle
                title="本月行课流量转化"
                time={YESTERDAY}
                containerStyle={{justifyContent: 'space-between'}}
            />
            <div>
                <Card style={{width: '100%', marginTop: 24}}>
                    <CommonSearchBar
                        loading={loading}
                        noCache
                        config={searchForm}
                        initialValues={initialValues}
                        onOk={handleOk}
                        onReset={handleReset}
                        onItemChange={handleItemChange}
                        onfetchOptions={handleFetchOptions}
                        selectOptions={selectOptions}
                    />
                </Card>
                <CommonTitle
                    type="subTitle"
                    title="一、本月短期班行课概览"
                />
                <Card style={{width: '100%'}}>
                    <div className="transform-report-first-img">
                        <img
                            alt=""
                            width="100%"
                            height={500}
                            src={result?.transformationThisMonthGeneralView?.picture?.pictureUrl}
                        />
                    </div>
                    <div className="transform-report-first-content">
                        <TextArea
                            className="transform-report-text-area"
                            value={result?.transformationThisMonthGeneralView?.text?.textContent}
                            bordered={false}
                            readOnly
                        />
                    </div>
                </Card>
                <CommonTitle
                    type="subTitle"
                    title="二、转化效率"
                />
                <Card style={{width: '100%'}}>
                    <div style={{marginBottom: 8}}>
                        <TransformTextCard
                            loading={loading}
                            onDownload={handleDownload}
                            onDetail={handleDetail}
                            dataSource={result?.transformationThisMonthConversionEfficiency?.cardList || []}
                        />
                    </div>
                    <div style={{marginBottom: 8}}>
                        <Row>
                            <EchartsPieCard
                                id={result?.transformationThisMonthConversionEfficiency?.pieUnit?.unitId}
                                span={12}
                                title={result?.transformationThisMonthConversionEfficiency?.pieUnit?.unitName ?? ''}
                                loading={loading}
                                onDetail={handleDetail}
                                onDownload={handleDownload}
                                onDrilling={handleDrilling}
                                pieUnit={result?.transformationThisMonthConversionEfficiency?.pieUnit}
                                labelCallback={params => {
                                    if (params.data.proportion < 0.05) {
                                        return;
                                    }
                                    return `${params.data.name}: ${parsePercent(params.data.proportion)}`;
                                }}
                                tooltipCallback={params =>
                                    `${params.data.name} <br/>
                                    订单数: ${numberHandle(params.data.value, 2)} <br/>
                                    订单占比: ${parsePercent(params.data.proportion) || '-'}`
                                }
                                onBack={handleBack}
                                drilingLevel={drilingLevel}
                            />
                            <EchartsLineCard
                                id={result?.transformationThisMonthConversionEfficiency?.lineUnit?.unitId}
                                data={result?.transformationThisMonthConversionEfficiency?.lineUnit}
                                loading={loading}
                                span={12}
                                title={result?.transformationThisMonthConversionEfficiency?.lineUnit?.unitName}
                                onBack={handleBack}
                                onDownload={handleDownload}
                                onDetail={handleDetail}
                                onDrilling={handleDrilling}
                                drilingLevel={drilingLevel}
                                grid={{left: '8%', right: '8%', bottom: 100}}
                                yAxisIndex={1}
                                key={result?.transformationThisMonthConversionEfficiency?.lineUnit?.unitId}
                                unitPercentIndex={1}
                                tooltip={params => {
                                    const tooltipList = params.map(chartItem => {
                                        const {seriesType, seriesName, name, value, data: {ROI}, marker} = chartItem;
                                        let result = '';

                                        if (seriesType === 'bar') {
                                            result = `${name}<br/>${marker} ${seriesName}: ${numberHandle(value, 2)}`;
                                        } else {
                                            result = `<br/>${marker} ${seriesName}: ${parsePercent(value)}<br/> ROI: ${numberHandle(ROI, 2)}`;
                                        }

                                        return result;
                                    });
                                    return tooltipList.join('');
                                }}
                            />

                        </Row>
                    </div>
                </Card>
                <CommonTitle
                    type="subTitle"
                    title="三、流量质量"
                    remark={result?.transformationThisMonthFlowQuality?.efficiencyText?.textContent}
                    containerStyle={{justifyContent: 'space-between'}}
                />
                <Card style={{width: '100%'}}>
                    <div style={{marginBottom: 8}}>
                        <ProgressCardList
                            dataSource={result?.transformationThisMonthFlowQuality?.cardList || []}
                            span={6}
                            loading={loading}
                            onDownload={handleDownload}
                            onDetail={handleDetail}
                        />
                    </div>
                    <div style={{marginBottom: 8}}>
                        <Row>
                            <EchartsLineCard
                                key={result?.transformationThisMonthFlowQuality?.lineUnit?.unitId}
                                id={result?.transformationThisMonthFlowQuality?.lineUnit?.unitId}
                                data={result?.transformationThisMonthFlowQuality?.lineUnit}
                                loading={loading}
                                span={12}
                                title={result?.transformationThisMonthFlowQuality?.lineUnit?.unitName ?? ''}
                                onBack={handleBack}
                                onDownload={handleDownload}
                                onDetail={handleDetail}
                                onDrilling={handleDrilling}
                                drilingLevel={drilingLevel}
                                grid={{left: '8%', right: '8%', bottom: 100}}
                                yAxisIndex={1}
                                rotate={30}
                                unitPercentIndex={1}
                                tooltip={params => formatTooltip(params, true)}
                            />
                            <EchartsPieCard
                                id={result?.transformationThisMonthFlowQuality?.pieUnit?.unitId}
                                span={12}
                                title={result?.transformationThisMonthFlowQuality?.pieUnit?.unitName ?? ''}
                                loading={loading}
                                onDetail={handleDetail}
                                onDownload={handleDownload}
                                pieUnit={result?.transformationThisMonthFlowQuality?.pieUnit}
                                onBack={handleBack}
                                onDrilling={handleDrilling}
                                drilingLevel={drilingLevel}
                                labelCallback={params => {
                                    if (params.data.proportion < 0.05) {
                                        return;
                                    }
                                    return `${params.data.name}: ${parsePercent(params.data.proportion)}
                                    \n 转化率: ${parsePercent(params.data.conversion_rate) || '-'}
                                    \n ROI: ${params.data.ROI && parseFloat(params.data.ROI).toFixed(2) || '-'}`;
                                }}
                                tooltipCallback={params =>
                                    `${params.data.name}: ${parsePercent(params.data.proportion)}<br/>
                                    转化率: ${parsePercent(params.data.conversion_rate) || '-'} <br/>
                                    ROI: ${params.data.ROI && parseFloat(params.data.ROI).toFixed(2) || '-'}`
                                }
                            />


                        </Row>
                    </div>
                </Card>
            </div>
            <DetailModal
                data={detailData}
                detailModalVisible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
            />
        </div>
    );
}
